//
//  SkySimCardHandler.m
//  BlueDemo
//
//  Created by wulanzhou on 16/3/14.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "SkySimCardHandler.h"


@interface SkySimCardHandler (){
    __block  NSInteger _onceOne;
}

/**
 *  超时计时器
 */
@property (nonatomic,strong) NSTimer *cardTimer;

/**
 *  要发送数据
 */
@property (nonatomic,strong) SkySimCardData *sendingSkyCmdDataPack;

/**
 *  取得数据回调
 *  @decodeModel  解析后的蓝牙数据
 *  @isOpenBle    YES:打开 NO:关闭
 */
@property (nonatomic,copy) void (^SkySimReceiveDataCompletedBlock) (SkySimCardData *decodeModel);

@end

@implementation SkySimCardHandler


+ (SkySimCardData *)decodeWithCmd:(SkySimCardHeadData *)cmd characteristicValue:(NSData *)characterValue{
    
    SkySimCardData *mod=nil;
    if (cmd) {
        
        if (cmd.bodyCmd==0x34) { //sim id
            mod=[SkyCmdGetCardID decodeSkySimCardWithData:characterValue];
        }
        else if (cmd.bodyCmd==0x35) { //下载SIM卡
            mod=[SkyCmdDownloadCardData decodeSkySimCardWithData:characterValue];
        }else if (cmd.bodyCmd==0x37) { //激活SIM卡卡号
            mod=[SkyCmdChangeCard decodeSkySimCardWithData:characterValue];
        }else if (cmd.bodyCmd==0x38) { //释放SIM卡卡号
            mod=[SkyCmdReleaseCard decodeSkySimCardWithData:characterValue];
        }else if (cmd.bodyCmd==0x42) {//SIM卡心跳包
            mod=[SkyCmdHeartBeat decodeSkySimCardWithData:characterValue];
        }else if (cmd.bodyCmd==0x46) {//查询SIM卡查对应索引数据状态
            mod=[SkyCmdSearchCardData decodeSkySimCardWithData:characterValue];
        }
        else if (cmd.bodyCmd==0x47) {//查询SIM卡状态
            mod=[SkyCmdSearchCardData decodeSkySimCardWithData:characterValue];
        }
    }
    
    return mod;
}

- (void)dealloc{
    
    [self removeObservers];
    //[self stopTimer];
}

- (id)init{
    
    if (self=[super init]) {
        _onceOne=0;
        
    }
    return self;
}

/**
 *  初始化
 *
 *  @param cmdSkyCardData 要发送的指令对象
 *
 *  @return
 */
- (id)initWithCmd:(SkySimCardData *)cmdSkyCardData{

    if (self=[super init]) {
        _onceOne=0;
        self.sendingSkyCmdDataPack=cmdSkyCardData;
    }
    return self;
}

/**
 *  设置接收数据回调
 *
 *  @param completed 数据回调
 */
- (void)setSkySimReceiveDataCompletionBlock:(void (^) (SkySimCardData *decodeModel))completed{
    self.SkySimReceiveDataCompletedBlock=completed;
}

/**
 *  开始计时
 */
- (void)startTimer{
    //[self stopTimer];
    self.cardTimer=[NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(cardIdLoadFinished) userInfo:nil repeats:NO];
    
}
/**
 *  停止计时
 */
- (void)stopTimer{
    if (self.cardTimer && [self.cardTimer isValid]) {
        [self.cardTimer invalidate];
    }
}

/**
 *  5秒内没有返回结果
 */
- (void)cardIdLoadFinished{
    [self cardCompletedWithModel:nil isOpen:YES];
    
}

/**
 *  结果回调
 *
 *  @param mod
 *  @param isOpen
 */
- (void)cardCompletedWithModel:(id)mod isOpen:(BOOL)isOpen{
    
    [self clearAllData];
    
    if (self.SkySimReceiveDataCompletedBlock) {
        self.SkySimReceiveDataCompletedBlock(mod);
    }
    
    self.SkySimReceiveDataCompletedBlock=nil;
}

/**
 *  清空数据
 */
- (void)clearAllData{
    _onceOne=0;
    self.sendingSkyCmdDataPack=nil;
    [self removeObservers];
    
    [self stopTimer];
}


/**
 *  通知监听
 */
- (void)addObservers{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recevieStateChanged:) name:kBLEStateChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recevieConnectSuccess:) name:kBLEConnectSetupNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveConnectFailed:) name:kBLEConnectFailedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recevieDataPackCompleted:) name:kBLEReceivePartialDataNotification object:nil];
}

/**
 *  移除通知
 */
- (void)removeObservers{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  蓝牙初始化完成
 *
 *  @param notification
 */
- (void)recevieStateChanged:(NSNotification *)notification{
    
    NSNumber *num=[notification object];
    if ([num integerValue]!=BLEStateOpen) {
        //表示蓝牙未开启
        [self cardCompletedWithModel:nil isOpen:NO];
    }
}

/**
 *  蓝牙连接状态
 *
 *  @param notification
 */
- (void)recevieConnectSuccess:(NSNotification *)notification{
    
    //延迟两秒发送
    [self performSelector:@selector(waitingSendData) withObject:nil afterDelay:2.0f];
}

//连接失败
- (void)receiveConnectFailed:(NSNotification *)notification{
    if (_onceOne==0) {
        //重连一次
        [[BLECentralManager shareInstance] startScan];
        
        _onceOne++;
    }else{ //返回结果
        [self cardCompletedWithModel:nil isOpen:YES];
    }
    
}

/**
 *  数据接收完成通知
 *
 *  @param notification
 */
- (void)recevieDataPackCompleted:(NSNotification *)notification{
    
    id item=[notification object];
    if (item) {
        SkySimCardData *mod=(SkySimCardData *)item;
        
        if (mod.bodyCmd==self.sendingSkyCmdDataPack.bodyCmd) { //相同指令的回调才返回
            [self cardCompletedWithModel:mod isOpen:YES];
        }
        //[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cardIdLoadFinished) object:nil];
    }
}


- (void)waitingSendData{
    //发送数据
    [[BLECentralManager shareInstance].getFirstConnector sendSkySimCardData:self.sendingSkyCmdDataPack];
    //30秒计时开始
    [self startTimer];
}



/**
 *  开始发送数据
 */
- (void)send{
    
    [self addObservers];
    
    //[self stopTimer];
    
    BLEConnector *ft=[BLECentralManager shareInstance].getFirstConnector;
    if (ft&&[ft isConnected]) { //表示已连接
        [self waitingSendData];
        
    }else{ //未连接则进行扫描连接
        [[BLECentralManager shareInstance] startScan];
    }
}

@end
